package com.security.control.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author imoot@gamil.com
 * @date 2018/12/17 0017 15:59
 */
@Component
public class MyUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    private Logger log = LoggerFactory.getLogger(MyUserDetailsService.class);

    //注入密码加密类
    @Autowired
    public PasswordEncoder passwordEncoder;

    //表单登录获取用户信息
    //正常开发中用用户类实现UserDetails接口，把相应的逻辑判断写入用户类的方法中
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("表单登录用户名：" + username);
        return buildUser(username);
    }

    //社交登录（第三方授权登录）获取用户信息
    //正常开发中用用户类实现SocialUserDetails接口，把相应的逻辑判断写入用户类的方法中
    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        log.info("社交登录用户Id：" + userId);
        return buildUser(userId);
    }

    //创建用户
    private SocialUserDetails buildUser(String userId) {
        String password = passwordEncoder.encode("123456");
        log.info("加密密码：" + password);
        //AuthorityUtils.commaSeparatedStringToAuthorityList("admin")把字符串转为相应的权限对象并放入集合中
        //需要注意springsecurity5以上版本使用spring提供的默认登录页面要注意：security5修改了密码格式，格式如下："{id}password"，id为加密格式对应的加密类（可以在PasswordEncoderFactories中查找加密类对应的id），password为加密后的密码
        //另一个注意事项为：如果使用前端页面发送的登录请求，则不需要修改格式："password"，password为加密后的密码
        //return new User(username, "{noop}123456", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));//new User(用户名，密码，权限集合)
        //注：在使用AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN")转换时需要与权限配置中访问链接所指定的"ADMIN"相同
        return new SocialUser(userId, password, true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER,ROLE_ADMIN"));//new User(用户名，密码，账户没有删除，账户没有过期，密码没有过期，账户没有冻结，权限集合)
    }
}
